class AccountController < ApplicationController

  # say something nice, you goof!  something sweet.
  def index
    redirect_to(:action => 'signup') unless logged_in? || User.count > 0
  end

  def login
    return unless request.post?
    self.current_user = User.authenticate(params[:login], params[:password])
    if logged_in?
      if params[:remember_me] == "1"
        self.current_user.remember_me
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      redirect_back_or_default(:controller => 'welcome', :action => 'index')
      flash[:notice] = "Logged in successfully"
    end
  end

  def signup
    @user = User.new((params[:user] || {}).merge(:share_contact_details => true, :signup_complete => false))
    return unless request.post?
    @user.save!
    flash[:notice] = :signup_thanks.l
    redirect_back_or_default(:controller => 'welcome', :action => 'index')
  rescue ActiveRecord::RecordInvalid
    render :action => 'signup'
  end
  
  def logout
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default(:controller => 'welcome', :action => 'index')
  end
  
  def forgot_password
    if request.post?
      u = User.find(:first, :conditions => ['email=?', params[:user][:email]])
      if u.nil?
        flash[:notice] = :email_not_found.localize_with_args(:email => "'#{params[:user][:email]}'")
      else
        host, port = request.host_with_port.split(":")
        u.send_new_password!(url_for(:controller => 'welcome', :host => host, :port => port || 80))
        flash[:notice] = :sent_new_password.localize_with_args(:email => params[:user][:email])
        redirect_to :action => 'login'
      end
    end
  end
  
end
